/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rs232_test;

//~--- non-JDK imports --------------------------------------------------------
import gnu.io.*;

//~--- JDK imports ------------------------------------------------------------

import java.io.*;

import java.util.*;

/**
 *
 * @author sf
 */
public class rs_test extends MainClass
        implements Runnable, SerialPortEventListener {

    /** Field description */
    String messageString = "Hello, world!";
    /** Field description */
    InputStream inputStream;
    /** Field description */
    OutputStream outputStream;
    /** Field description */
    CommPortIdentifier portId;
    /** Field description */
    MainClass pubMain;
    /** Field description */
    SerialPort serialPort;

    /**
     * Constructs ...
     *
     *
     * @param main
     */
    rs_test(MainClass main) {
        pubMain = main;

        Enumeration portList;
        String defaultPort = "COM4";
        boolean portFound = false;

        portList = CommPortIdentifier.getPortIdentifiers();

        while (portList.hasMoreElements()) {
            portId = (CommPortIdentifier) portList.nextElement();

            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                if (portId.getName().equals(defaultPort)) {
                    System.out.println("Found port: " + defaultPort);
                    portFound = true;

                    // initalize serial port
                    System.out.println("punto critico");

                    try {
                        serialPort = (SerialPort) portId.open("SimpleReadApp",
                                2000);
                    } catch (PortInUseException e) {
                    }

                    try {
                        inputStream = serialPort.getInputStream();
                    } catch (IOException e) {
                    }

                    try {
                        serialPort.addEventListener(this);
                    } catch (TooManyListenersException e) {
                    }

                    // activate the DATA_AVAILABLE notifier
                    serialPort.notifyOnDataAvailable(true);

                    try {

                        // set port parameters
                        serialPort.setSerialPortParams(9600,
                                SerialPort.DATABITS_8,
                                SerialPort.STOPBITS_1,
                                SerialPort.PARITY_NONE);
                    } catch (UnsupportedCommOperationException e) {
                    }
                }
            }
        }
    }

    public void serialEvent(SerialPortEvent event) {
        Rs485 rs485 = new Rs485((char)0x0201);

        switch (event.getEventType()) {
            case SerialPortEvent.BI:
            case SerialPortEvent.OE:
            case SerialPortEvent.FE:
            case SerialPortEvent.PE:
            case SerialPortEvent.CD:
            case SerialPortEvent.CTS:
            case SerialPortEvent.DSR:
            case SerialPortEvent.RI:
            case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                break;

            case SerialPortEvent.DATA_AVAILABLE:

                // we get here if data has been received
                byte[] readBuffer = new byte[20];
                //byte[] a;

                try {

                    // read data
                    while (inputStream.available() > 0) {
                        //byte rs485RxChar;
                        //int numBytes = inputStream.read();

                        do {
                            rs485.setrs485RxChar((byte) inputStream.read());
                            System.out.print(rs485.getCommand());

                        } while (!(rs485.isPacketComplete() | rs485.isErrState()|rs485.isPacketReady()));
                        if (rs485.isPacketForMe()) readBuffer = rs485.rxCommPack.c485Buf;
                        else readBuffer = null;
                    }

                    // print data
                    String result = new String(readBuffer);

                    System.out.println("Read: " + result.trim());
                    pubMain.setStringUpdate(result.trim());
                    pubMain.setRxPackUpdate(rs485.rxCommPack);
                } catch (IOException e) {
                }

                break;
        }
    }

    public void initwritetoport() {

        // initwritetoport() assumes that the port has already been opened and
        // initialized by "public nulltest()"
        try {

            // get the outputstream
            outputStream = serialPort.getOutputStream();
        } catch (IOException e) {
        }

        try {

            // activate the OUTPUT_BUFFER_EMPTY notifier
            serialPort.notifyOnOutputEmpty(true);
        } catch (Exception e) {
            System.out.println("Error setting event notification");
            System.out.println(e.toString());
            System.exit(-1);
        }
    }

    public void writetoport() {
        System.out.println("Writing \"" + messageString + "\" to " + serialPort.getName());

        try {

            // write string to serial port
            outputStream.write(messageString.getBytes());
        } catch (IOException e) {
        }
    }
}


//~ Formatted by Jindent --- http://www.jindent.com
